package group.sshd.redis.client.terminal.config;

import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author bolin
 * @create 2020-11
 * @desc
 */
@Component
public class RedissonFactory {

    @Autowired
    private RedisConfig redisConfig;

    private static final Map<String, RedissonClient> clientMap = new HashMap<>();

    public RedissonClient connRedis(String name) {
        if (!redisConfig.getNodeMap().containsKey(name)) {
            throw new IllegalArgumentException();
        }
        if (!clientMap.containsKey(name)) {
            synchronized (clientMap) {
                if (!clientMap.containsKey(name)) {
                    Config config = new Config();
                    Map<String, String> map = redisConfig.getNodeMap().get(name);
                    config.useSingleServer()
                            .setConnectionPoolSize(1)
                            .setConnectionMinimumIdleSize(1)
                            .setAddress(map.get("address"))
                            .setPassword((map.get("password") == null || map.get("password").length() == 0) ? null : map.get("password"));
                    RedissonClient client = Redisson.create(config);
                    clientMap.put(name, client);
                }
            }
        }
        return clientMap.get(name);
    }


    public void close(String name) {
        try {
            RedissonClient redissonClient = clientMap.remove(name);
            if (redissonClient != null) {
                redissonClient.shutdown();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
